import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { Alert, ScrollView, View, StyleSheet, TouchableOpacity } from 'react-native';
import { SearchBar, SideMenu, Text, Button, Icon } from 'react-native-elements';
import { LaundryGrid, PremiumLaundryGrid } from './components/ClothGrid';
import ClothGridItem from './components/ClothGridItem';
import ClothCategoryHorBar from './components/ClothCategoryHorBar';
import ShoppingCart from './components/ShoppingCart';
import { primaryColor, toast, executor, calculateInsurancePrice } from './utils';
import { getDefaultAddress, setNewOrderItems, getNewOrderItems } from './clientStorage';

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    flex: 1
  },
  titlebar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#e1e8ee'
  },
  fill: {
    flex: 1
  },
  checkout: {
    color: 'white',
    fontWeight: 'bold'
  },
  checkoutContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 16,
    paddingHorizontal: 8,
  },
});

class LaundryPricingPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: (screenProps.chinese?'选择要清洗衣物':'Choose Items'),
    };
  };
  state = { isOpen: false, selects: [] }
  componentDidMount() {
    getNewOrderItems(this.props.navigation.state.params.type==='premiumlaundry')
      .then(selects => {
        const needLoad = selects&&(selects.filter(item => item.needLoad).length>0);
        if (needLoad) {
          executor(this.props.loadClothes, selects.map(item => item.id))
            .then(({res}) => {
              if (res&&res.loadClothes) {
                const newSelects = res.loadClothes.map(item => {
                  const select = selects.find(node => node.id===item.id);
                  return {...select, ...item};
                });
                this.setState({selects: newSelects});
                setNewOrderItems(this.props.navigation.state.params.type==='premiumlaundry', newSelects);
              }
            })
        } else {
          this.setState({selects: selects||[]});
        }
      });
    if (this.props.user) {
      this.props.navigation.setParams({user: this.props.user});
    }
  }
  componentWillReceiveProps(nextProps) {
    if (!this.props.user&&nextProps.user) {
      this.props.navigation.setParams({user: nextProps.user});
    }
  }
  onSideMenuChange = (isOpen) => this.setState({isOpen: isOpen})
  onToggleSideMenu = () => this.setState({isOpen: !this.state.isOpen})
  onSelectItem = (cloth) => {
    // if (!this.props.user) {
    //   Alert.alert(
    //     this.props.screenProps.chinese?`您还没有登录`:`You havn't sign in`,
    //     '',
    //     [
    //       {text: this.props.screenProps.chinese?'稍后':'Later'},
    //       {text: this.props.screenProps.chinese?'登录':'Sign In', onPress: () => this.props.navigation.navigate('Login')},
    //     ],
    //     { cancelable: true }
    //   );
    //   return;
    // }

    const chinese = this.props.screenProps.chinese;
    let selects = this.state.selects;
    let index = selects.findIndex(item => item.id===cloth.id);
    if (index<0) {
      selects = [cloth, ...this.state.selects];
    } else {
      selects = [selects[index], ...selects.slice(0,index), ...selects.slice(index+1)];
    }

    if (cloth.checkDescription&&cloth.description) {
      Alert.alert(
        cloth.name,
        cloth.description,
        [
          {text: chinese?'取消':'Cancel'},
          {text: chinese?'确定':'OK', onPress: () => {
            this.onSelectUpdate(selects);
            this.setState({isOpen: true, scrollToTop: Date.now()});
          }},
        ],
        { cancelable: true }
      );
    } else {
      this.onSelectUpdate(selects);
      this.setState({isOpen: true, scrollToTop: Date.now()});
    }
  }
  onSelectUpdate = (selects) => {
    this.setState({selects});
    this.updateLocalStorage(selects);
  }
  updateLocalStorage = (selects) => {
    setNewOrderItems(this.props.navigation.state.params.type==='premiumlaundry', selects);
  }
  onSearchChange = (search) => {
    this.setState({search});
  }
  onSelectCategory = (category) => {
    this.setState({categoryId: category.id})
  }
  onGoGuide = () => {
    this.props.navigation.navigate('LaundryGuide',
      {type: this.props.navigation.state.params.type});
  }
  onCheckout = () => {
    const navigation = this.props.navigation;
    const screenProps = this.props.screenProps;

    getNewOrderItems(navigation.state.params.type==='premiumlaundry')
      .then(selects => {
        let items = [];
        selects&&selects.map(({id,dryCount,washCount,ironCount,insurance}) => {
          if (dryCount>0) {
            items.push({id,type:'dry',count:dryCount,insurance});
          }
          if (washCount>0) {
            items.push({id,type:'wash',count:washCount,insurance});
          }
          if (ironCount>0) {
            items.push({id,type:'iron',count:ironCount,insurance});
          }
        });
        
        if (items.length===0) {
          Alert.alert(
            screenProps.chinese?'请选择衣物':'Please choose your items',
            screenProps.chinese?`我们正在升级我们的快速下单系统，目前请您手动选择要清洗的衣物，感谢`:`We're now improving our quick order process, at this time please select your items for cleaning manually. Thank you.`,
            [
              {text: screenProps.chinese?'确定':'OK'},
            ],
            { cancelable: true }
          );
        } else {
          navigation.navigate(navigation.state.params.stepper?navigation.state.params.stepper[navigation.state.params.stepIndex]:'CheckoutDeliveryDate', {
            stepper: ['CheckoutDeliveryDate', 'CheckoutPayment', 'CheckoutOverview'],
            stepIndex: 0,
            pickupCalendar: true,
            deliveryCalendar: true,
            ...navigation.state.params,
            items,
          });
        }
      });
  }
  renderContent = (user, type, totalPrice, totalCount) => {
    const { chinese } = this.props.screenProps;

    return (
      <View style={styles.container}>
        <ScrollView removeClippedSubviews={true}>
          <View style={styles.titlebar}>
            <Button icon={{name: 'shopping-cart',color:'#86939e'}} color='#86939e'
              title={`$${totalPrice.toFixed(2)} (${totalCount}${chinese?'件':' items'})`} backgroundColor='#e1e8ee' onPress={this.onToggleSideMenu}/>
            <View style={styles.fill}>
              <SearchBar inputStyle={{height:50}} lightTheme round textInputRef='search'
                onChangeText={this.onSearchChange} placeholder={chinese?'查询衣物':'Search item'}/>
            </View>
          </View>
          {!this.state.search&&(type==='laundry')&&<ClothCategoryHorBar chinese={chinese} select={this.state.categoryId} onSelect={this.onSelectCategory}/>}
          {type==='premiumlaundry'?
            <PremiumLaundryGrid search={this.state.search} onSelect={this.onSelectItem} chinese={chinese}
              type={type}/>:
            <LaundryGrid search={this.state.search} onSelect={this.onSelectItem} chinese={chinese}
              type={type} categoryId={this.state.categoryId}/>
          }
        </ScrollView>
      </View>
    );
  }
  render() {
    const { config, defaultAddress, lockerBag, user } = this.props;
    const { chinese } = this.props.screenProps;
    const { type, business } = this.props.navigation.state.params;
    const { selects } = this.state;

    const totalCount = selects.length===0?0:selects.map(({washCount=0, dryCount=0, ironCount=0}) =>
      washCount+dryCount+ironCount).reduce((a, b) => a+b);
    const totalPrice = selects.length===0?0:selects.map((item) => {
      const {washCount=0, dryCount=0, ironCount=0,
        wash, washD, dry, dryD, iron, ironD} = item;
      return (washCount*(washD||wash)+dryCount*(dryD||dry)+ironCount*(ironD||iron))+calculateInsurancePrice(item, config);
    }).reduce((a,b)=>a+b);

    let valueForFree = 0, deliveryFee = 0;
    if (!business&&defaultAddress&&defaultAddress.minialOrderPrice&&defaultAddress.deliveryFee&&(totalPrice<defaultAddress.minialOrderPrice)) {
      valueForFree = defaultAddress.minialOrderPrice-totalPrice;
      deliveryFee = defaultAddress.deliveryFee;
    }


    return (
      <SideMenu isOpen={this.state.isOpen} onChange={this.onSideMenuChange}
        menu={<ShoppingCart chinese={chinese} scrollToTop={this.state.scrollToTop} selects={selects}
          onSelectUpdate={this.onSelectUpdate} navigation={this.props.navigation} totalCount={totalCount}
          totalPrice={totalPrice} valueForFree={valueForFree} deliveryFee={deliveryFee} type={type}
          lockerBag={lockerBag} onCheckout={this.onCheckout}/>}>
        {this.renderContent(user, type, totalPrice+deliveryFee, totalCount)}
      </SideMenu>
    );
  }
}

export default compose(
  graphql(gql`
    query LaundryPricingPage {
      config {
        insuranceMultiple
        esuranceCharge
      }
      defaultAddress {
        id
        minialOrderPrice
        deliveryFee
      }
      user {
        id
        hasLockerBag
      }
      lockerBag {
        id
        dry
        dryD
      }
    }
  `, {
    props: ({data:{config, user, lockerBag, defaultAddress, loading}}) => {
      return {
        config,
        defaultAddress,
        lockerBag: user&&!user.hasLockerBag&&lockerBag,
        user,
        loading
      };
    }
  }),
  graphql(gql`
    mutation loadClothes($ids:[String]!) {
      loadClothes(ids:$ids) {
        ...ClothGridItem
      }
    }
    ${ClothGridItem.fragments.cloth}
  `, {
    props: ({ownProps:{screenProps}, mutate}) => {
      return {
        loadClothes: (ids) => mutate({variables:{ids}})
      };
    }
  })
)(LaundryPricingPage);

